package test;

import org.junit.Test;

public class NewTon {
    //牛顿迭代法
    public double sqrt(int x) {
        //f(x) = x^2  f'(x) = 2x   -f(x) = 2x * (xNext - x) => xNext = x - f(x) / (2x) = x - x / 2
        double tar = x;
        double res = x / 2.0;
        while (Math.abs(res * res - tar) > 1e-7) {
            res = res - (res * res - tar) / (2 * res); 
        }

        return res;
    }

    @Test
    public void test() {
        System.out.println(sqrt(2));
    }
}
